import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;

import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;


public class Lloguer {

    /**
     * @return the JDOM document parsed from the file.
     */
    public static Document readDocument() {
        try {
            SAXBuilder builder = new SAXBuilder();
            Document anotherDocument = builder.build(new File("xml/lloguers.xml"));
            return anotherDocument;
        } catch(JDOMException e) {
            e.printStackTrace();
        } catch(NullPointerException e) {
            e.printStackTrace();
        } catch(java.io.IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return a JDOM Document.
     */
    public static Document createDocument() {

        // Create the root element
        Element lloguersElement = new Element("llistat-lloguers");
        //create the document
        Document myDocument = new Document(lloguersElement);

        return myDocument;
    }
    
    public static Document addEntryToDocument(Document myDocument) {

		HashMap<String, Double> priceInfo = new HashMap<String, Double>();
		priceInfo.put("Economic", 200.0);
		priceInfo.put("Semi-Luxe", 400.0);
		priceInfo.put("Luxe", 699.95);
		priceInfo.put("Limusina", 1234.5);

		Scanner in = new Scanner(System.in);
		
		Element lloguer = new Element("lloguer");
		System.out.println("Insereix les dades del lloguer:");
		
		System.out.println("Model:(Economic/Semi-Luxe/Luxe/Limusina)");
		String model = in.nextLine();
		System.out.println("Motor:(Gasolina/Diesel)");
		String motor = in.nextLine();
		System.out.println("Quantitat: ");
		String quantitat = in.nextLine();
		System.out.println("Dies: ");
		String dies = in.nextLine();
		System.out.println("Descompte: *.*");
		String descompte = in.nextLine();
		System.out.println("Guardant Reserva...");
		
		Double price = priceInfo.get(model);
		price = price == null ? 299.95 : price; // Si no esta al llistat
												// s'assigna el preu per defecte
		price *= motor.equals("Gasolina") ? 1.1 : 0.9;
		price *= Integer.parseInt(dies);
		price *= Integer.parseInt(quantitat);
		price -= price * (Double.parseDouble(descompte) / 100);
		System.out.println("");
		System.out.println("Preu Final: " + price);
		System.out.println("");

		lloguer.addContent(new Element("model").addContent(model));
		lloguer.addContent(new Element("motor").addContent(motor));
		lloguer.addContent(new Element("quantitat").addContent(quantitat));
		lloguer.addContent(new Element("dies").addContent(dies));
		lloguer.addContent(new Element("descompte").addContent(descompte));
		lloguer.addContent(new Element("price").addContent(price.toString()));
		
		Element llistat = myDocument.getRootElement();
		llistat.addContent(lloguer);
    	
    	return myDocument;
    }

    /**
     * This method shows how to use XMLOutputter to output a JDOM document to
     * the stdout.
     * @param myDocument the JDOM document.
     */
    public static void outputDocument(Document myDocument) {
        try {
            // XMLOutputter outputter = new XMLOutputter("  ", true);
            XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
            outputter.output(myDocument, System.out);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method shows how to use XMLOutputter to output a JDOM document to
     * a file located at xml/myFile.xml.
     * @param myDocument the JDOM document.
     */
    public static void outputDocumentToFile(Document myDocument) {
        //setup this like outputDocument
        try {
            // XMLOutputter outputter = new XMLOutputter("  ", true);
            XMLOutputter outputter = new XMLOutputter();

            //output to a file
            FileWriter writer = new FileWriter("xml/lloguers.xml");
            outputter.output(myDocument, writer);
            writer.close();

        } catch(java.io.IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method takes a JDOM document in memory, an xsl file at xml/lloguers.xsl,
     * and outputs the results to stdout.
     * @param myDocument the JDOM document.
     */
    public static void executeXSL(Document myDocument) {
		try {
			TransformerFactory tFactory = TransformerFactory.newInstance();
            // Make the input sources for the XML and XSLT documents
            org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter();
            org.w3c.dom.Document domDocument = outputter.output(myDocument);
            javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument);
            StreamSource xsltSource = new StreamSource(new FileInputStream("xml/lloguers.xsl"));
			//Make the output result for the finished document
            /*
             * Note that here we are just going to output the results to the
             * System.out, since we don't actually have a HTTPResponse object
             * in this example
             */
            //StreamResult xmlResult = new StreamResult(response.getOutputStream());
            StreamResult xmlResult = new StreamResult(System.out);
			//Get a XSLT transformer
			Transformer transformer = tFactory.newTransformer(xsltSource);
			//do the transform
			transformer.transform(xmlSource, xmlResult);
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(TransformerConfigurationException e) {
            e.printStackTrace();
		} catch(TransformerException e) {
            e.printStackTrace();
        } catch(org.jdom.JDOMException e) {
            e.printStackTrace();
        }
	}

    /**
     * Main method that allows the various methods to be used.
     * It takes a single command line parameter.  If none are
     * specified, or the parameter is not understood, it prints
     * its usage.
     */
    public static void main(String argv[]) {
        if(argv.length == 1) {
            String command = argv[0];
            if(command.equals("reset")) outputDocumentToFile(createDocument());
            else if(command.equals("lloguer")) outputDocumentToFile(addEntryToDocument(readDocument()));
            else if(command.equals("llistar")) outputDocument(readDocument());
            else if(command.equals("xsl")) executeXSL(readDocument());
            else {
                System.out.println(command + " is not a valid option.");
                printUsage();
            }
        } else {
            printUsage();
        }
    }

    /**
     * Convience method to print the usage options for the class.
     */
    public static void printUsage() {
        System.out.println("Usage: Lloguer [option] \n on opcio es una de les seguents:");
        System.out.println("  reset   - deixa la llista de lloguers buida.");
        System.out.println("  lloguer - obte per teclat les dades del lloguer i les afegeix al xml.");
        System.out.println("  llistar - llista tots els lloguers en xml.");
        System.out.println("  xsl     - llista els lloguers en html.");
    }
}
